#pragma once

#include <AVUIColumnDefinition.h>
#include <AVUIObjectCollection.h>

namespace AVUI {

class Grid;

class ColumnDefinitionCollection : public TObjectCollection<ColumnDefinition>
{
public:
    DECLARE_ELEMENT(ColumnDefinitionCollection, ObjectCollectionBase);
    ColumnDefinitionCollection(Grid* pOwner) : m_pOwner(pOwner) { }

protected:

	virtual void ClearItems()
	{
		for(int idx = 0; idx < get_Count(); idx++)
		{
			OnRemove((*this)[idx]);
		}

		TObjectCollection<ColumnDefinition>::ClearItems();
		OnCollectionChanged();
	}

	virtual void InsertItem(int index, ColumnDefinition* pItem)
	{
		TObjectCollection<ColumnDefinition>::InsertItem(index, pItem);

		OnAdd(pItem);
		OnCollectionChanged();
	}

	virtual void RemoveItem(int index)
	{
		TRefCountedPtr<ColumnDefinition> pOldValue = (*this)[index];
		TObjectCollection<ColumnDefinition>::RemoveItem(index);

		OnRemove(pOldValue);
		OnCollectionChanged();
	}

	virtual void SetItem(int index, ColumnDefinition* pItem)
	{
		TRefCountedPtr<ColumnDefinition> pOldValue = (*this)[index];
		TObjectCollection<ColumnDefinition>::SetItem(index, pItem);

		OnRemove(pOldValue);
		OnAdd(pItem);
		OnCollectionChanged();
	}

private:
    void OnCollectionChanged();

    void OnAdd(ColumnDefinition* pAdd)
    {
        pAdd->set_Owner(m_pOwner);
        ((FrameworkElement*)m_pOwner)->AddLogicalChild(pAdd);
    }

    void OnRemove(ColumnDefinition* pRemove)
    {
        ((FrameworkElement*)m_pOwner)->RemoveLogicalChild(pRemove);
        pRemove->set_Owner(NULL);
    }


    Grid* m_pOwner;
};


}; // namespace AVUI
